package pe.gob.osinergmin.interfase_siaf.dac.dao.impl;

import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import pe.gob.osinergmin.interfase_siaf.dac.dao.BancoDao;
import pe.gob.osinergmin.interfase_siaf.dac.domain.Banco;

@Repository("bancoDao")
public class BancoDaoImpl implements BancoDao {

    private final Log logger = LogFactory.getLog(getClass());
	
	
	private NamedParameterJdbcTemplate jdbcParameterTemplateData;	
	private JdbcTemplate jdbcTemplateData;	
	
	
	
	@Autowired
	public void SetDataSource(DataSource dataSourceData){
		this.jdbcTemplateData = new JdbcTemplate(dataSourceData);
		this.jdbcParameterTemplateData = new NamedParameterJdbcTemplate(dataSourceData);
		
	}
	
	
	/**DECLARACION DE SQL**/
	private static final String SQL_SELECT_BANCO ="SELECT * FROM banco ";
	private static final String SQL_SELECT_BANCO_PARAMETER ="SELECT * FROM banco WHERE banco =:banco";
	private static final String SQL_SELECT_BANCO_PARAMETER1 ="SELECT * FROM banco WHERE nombre =:nombre";

	
	private static final String SQL_SELECT_BANCO_PARAMETER3 ="SELECT COUNT(banco) FROM banco WHERE banco =:banco";
	
	
	@Override
	public List<Banco> listarBanco() {
		logger.info("Ingresando a listar bancos"); 
		RowMapper<Banco> lista = ParameterizedBeanPropertyRowMapper.newInstance(Banco.class);
		return this.jdbcTemplateData.query(SQL_SELECT_BANCO, lista);
	}

	@Override
	public List<Banco> listarBancoParameter(Banco banco) {
		logger.info("Ingresando a listar bancos parameters"); 
		SqlParameterSource parameters = new BeanPropertySqlParameterSource(banco);
		RowMapper<Banco> lista = ParameterizedBeanPropertyRowMapper.newInstance(Banco.class);
		if(StringUtils.isNoneBlank(banco.getBanco())){ 
			return this.jdbcParameterTemplateData.query(SQL_SELECT_BANCO_PARAMETER, parameters, lista);	
		}else if(StringUtils.isNoneBlank(banco.getNombre())){
			return this.jdbcParameterTemplateData.query(SQL_SELECT_BANCO_PARAMETER1, parameters, lista);	
		}else{
			return null;
		}			
	}
	
	@Override
	public int verificarBanco(Banco b) throws Exception {		 
		SqlParameterSource parameters = new BeanPropertySqlParameterSource(b);		
	    return this.jdbcParameterTemplateData.queryForInt(SQL_SELECT_BANCO_PARAMETER3, parameters);	
	}

}
